<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<title>wake on lan</title>
		<link rel="stylesheet" type="text/css" href="css/mui.min.css" />
		<script src="js/mui.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/backup.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			.title {
				margin: 20px 15px 7px;
				color: #6d6d72;
				font-size: 15px;
			}
		</style>
		<script type="text/javascript">
			function First() {
				mui.alert('1.随意输入喜欢的用户名登录。\n2.添加局域网电脑（请保证已经开启网络唤醒功能）。', '使用说明', function() {});
			}
		</script>
	</head>

	<body>
		<header id="header" class="mui-bar mui-bar-nav">
			<h1 class="mui-title">访问wol.xiao3.top远控</h1>
		</header>

		<div class="mui-content">
			<div class="mui-content-padded">
				<button type="button" class="mui-btn mui-btn-primary mui-btn-block mui-btn-outlined" onclick="First()">首次使用说明</button>
			</div>
			<div class="mui-card">
				<ul class="mui-table-view">
					<li class="mui-table-view-cell">
						<div class="mui-input-row">
							<label>用户名</label>
							<input id="userName" type="text" class="" placeholder="待输入" value="">
						</div>
						<button id="loginbtn" type="button" class="mui-btn mui-btn-primary">登录</button>
						<button id="logoutbtn" type="button" class="mui-btn mui-btn-danger" style="display: none;">退出</button>
					</li>
				</ul>
			</div>
			<div id="cView" class="" style="display: none;">
				<div class="title">
					电脑列表<span id="clientstatus">（）</span>
				</div>
				<div class="mui-card">
					<ul id="pclist" class="mui-table-view">
						<li class="mui-table-view-cell">列表为空</li>
					</ul>
				</div>
				<div class="mui-card">
					<ul class="mui-table-view">
						<li class="mui-table-view-cell mui-collapse" id="addPCLi">
							<a class="mui-navigate-right" href="#">添加电脑</a>
							<div class="mui-collapse-content">
								<form class="mui-input-group">
									<div class="mui-input-row">
										<label>别名</label>
										<input id="pcname" type="text" class="mui-input-clear" placeholder="必填" value="">
									</div>
									<div class="mui-input-row">
										<label>mac地址</label>
										<input id="pcmac" type="text" class="mui-input-clear" placeholder="必填(FF-FF-FF-FF-FF-FF)" value="">
									</div>
									<div class="mui-input-row">
										<label>ip</label>
										<input id="pcip" type="text" class="mui-input-clear" placeholder="可选" value="">
									</div>
									<div class="mui-button-row">
										<button id="addpc" class="mui-btn mui-btn-primary" type="button" onclick="return false;">添加</button>
									</div>
									<div class="mui-button-row">
										<button id="getOnlives" class="mui-btn mui-btn-success" type="button" onclick="return false;">获取在线设备列表（点击列表填入）</button>
									</div>
									<div class="">
										<ul id="onLives" style="padding: 0;">
											<center>点击按键获取</center>
										</ul>
									</div>
								</form>
							</div>
						</li>
					</ul>
				</div>
			</div>
			<div class="title">
				日志
			</div>
			<div class="mui-input-row" style="margin: 10px 10px;">
				<textarea id="logs" rows="13" placeholder="日志" readonly="ture" style="margin: 0;font-size: 12px;line-height: 15px;padding: 5px;"></textarea>
			</div>
		</div>
	</body>
	<script type="text/javascript">
		//全局变量
		var codeSave = 200
		var codeLogout = 100 //退出
		var codeLogin = 101 //登陆
		var codeSetPC = 102 //设置电脑
		var codeWol = 666 //唤醒
		var codeExist = 998 //不可重复登录
		var codeError = 999 //错误
		var codeHeartbeat = 1000 //心跳
		var typeClient = 1 //客户端
		var typeControl = 2 //控制端


		var isConnect = false;
		var isLogIN = false;
		var Cname = "hello";
		var Ctype = typeClient;
		var PcList = new Array();
		var KeepAliveInterval = 0;
		var reflashInterval = 0;
		var UpdatePCStatusInterval = 0;
		var WebSocketURL = "ws://192.168.31.11:8066/ws";
		var WebSocketURL = "ws://172.16.0.112:8066/ws";
		var WebSocketURL = "ws://wol.xiao3.top:8066/ws";
		var WOLPort = 9;
		var MyWebSocket;
		var OnLivePC = new Array();
		//页面初始化
		document.addEventListener('plusready', function() {
			//console.log("所有plus api都应该在此事件发生后调用，否则会出现plus is undefined。")
			$("#loginbtn").attr("disabled", true);
			$("#addpc").attr("disabled", true);
			//"38:d5:47:af:7f:1a"
			//"30:9C:23:A3:40:52"
			if (IsWifi()) {
				WsConnect();
				ListenBtnOn();
				$("#clientstatus").text("（APP局域网IP：" + GetIP() + "）");
			} else {
				alert("请连接WIFI再启动APP！");
				plus.runtime.quit();
			}
		});
	</script>
	<script type="text/javascript">
		//定时器模块

		//保持ws连接
		function StartKeepAlive(sec) {
			StopKeepAlive();
			KeepAliveInterval = setInterval(function() {
				SendHeartbeat();
			}, sec * 1000);
		}

		function StopKeepAlive() {
			if (KeepAliveInterval != 0) {
				clearInterval(KeepAliveInterval);
			}
		}


		//定时刷新设备列表
		function StartReflash(sec) {
			StopReflash();
			SendGetPCList();
			reflashInterval = setInterval(function() {
				SendGetPCList();
			}, sec * 1000);
		}

		function StopReflash() {
			if (reflashInterval != 0) {
				clearInterval(reflashInterval);
			}
		}

		//定时刷新设备状态
		function StartUpdatePCStatus(sec) {
			StopUpdatePCStatus();
			UpdatePCStatusInterval = setInterval(function() {
				for (var i = 0; i < PcList.length; i++) {
					if (IsPCLive(PcList[i].ip)) {
						PcList[i].status = 1;
					} else {
						PcList[i].status = 0;
					}
				}
				SendSave();
			}, sec * 1000);
		}

		function StopUpdatePCStatus() {
			if (UpdatePCStatusInterval != 0) {
				clearInterval(UpdatePCStatusInterval);
			}
		}
	</script>

	<script type="text/javascript">
		//页面交互

		function ListenBtnOn() {
			$("#getOnlives").on('click', function() {
				$("#onLives").html("加载中...");
				PingIP();
			});
			$("#loginbtn").on('click', function() {
				LogIn();
			});
			$("#logoutbtn").on('click', function() {
				SendLogout();
				LogOut();
				isLogIN = false;
			});
			$("#addpc").on('click', function() {
				var pcname = $("#pcname").val();
				var pcmac = $("#pcmac").val();
				pcmac = pcmac.toUpperCase();
				var pcip = $("#pcip").val();

				if (pcname.length < 1) {
					mui.alert("别名不能为空！", '提示', function() {});
					return;
				}
				//mac地址正则表达式 
				var reg_name = /[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}-[A-F\d]{2}/;
				if (!reg_name.test(pcmac)) {
					mui.alert("mac地址格式不正确！mac地址格式为FF-FF-FF-FF-FF-FF", '提示', function() {});
					return;
				}
				if (SendAddPC(pcname, pcmac, pcip)) {
					$("#addPCLi").removeClass("mui-active");
				} else {
					mui.alert("mac已存在", '提示', function() {});
				}
			});
		}

		function SetIsLogin(is) {
			if (is) {
				$("#userName").attr("disabled", true);
				$("#loginbtn").hide();
				$("#logoutbtn").show();
				$("#cView").show();
				if (!isLogIN) {
					ShowLog("已登录");
					isLogIN = is;
				}
			} else {
				$("#userName").attr("disabled", false);
				$("#loginbtn").show();
				$("#logoutbtn").hide();
				$("#cView").hide();
				ShowLog("已退出");
			}
		}

		function LogIn() {
			if ($("#userName").val().length == 0) {
				mui.alert('请输入用户名', '提示', function() {});
				return;
			}
			Cname = $("#userName").val();
			StartReflash(5);
			StartUpdatePCStatus(60);
		}


		function LogOut() {
			Cname = "";
			PcList = new Array();
			StopUpdatePCStatus();
			StopReflash();
			ClearPCList();
			SetIsLogin(false);
		}

		function SetConnectStatus(is) {
			if (is) {
				ShowLog("服务器已连接");
				isConnect = true;
				$("#loginbtn").attr("disabled", false);
				$("#addpc").attr("disabled", false);
				if (isLogIN) {
					LogIn();
				}
			} else {
				ShowLog("服务器已断开");
				if (isLogIN) {
					LogOut();
				}
				isConnect = false;
				$("#loginbtn").attr("disabled", true);
				$("#addpc").attr("disabled", true);
			}
		}


		function ShowLog(t) {
			console.log(t);
			var myDate = new Date()
			$("#logs").text(myDate.Format("MM月dd日hh:mm:ss：\n") + t + "\n" + $("#logs").text());
		}

		function ClearPCList() {
			var ul = $("#pclist").html("");
			if (PcList.length == 0) {
				ul.html('<li class="mui-table-view-cell">列表为空</li>');
			}
		}

		//
		function ShowPCList() {
			ClearPCList();
			var ul = $("#pclist");
			for (var i = 0; i < PcList.length; i++) {
				var name = PcList[i].name + "(" + PcList[i].mac + ")(" + PcList[i].status + ")"; //+"(" + PcList[i].ip + ")";
				var li = $("<li>").addClass("mui-table-view-cell").attr({
					id: 'p-' + i
				}).text(name);
				//var status = $("<span>").text(PcList[i].status);
				var wakeBtn = $("<button>").addClass("mui-btn mui-btn-primary").text("唤醒").attr("mac", PcList[i].mac);
				wakeBtn.on('click', function() {
					//PCListBtnOn($(this), 1);
					var btn = $(this);
					var btnArray = ['否', '是'];
					mui.confirm('确认？', '将执行本地测试唤醒', btnArray, function(e) {
						if (e.index == 1) {
							UDPWOL("255.255.255.255", WOLPort, btn.attr("mac"));
						}
					})
				});

				var delBtn = $("<button>").addClass("mui-btn mui-btn-danger").text("删除").css("right", "80px");
				delBtn.on('click', function() {
					PCListBtnOn($(this), 2);
				});
				ul.append(li.append(wakeBtn, delBtn));
			}
		}

		//设备列表按钮
		function PCListBtnOn(btn, type) {
			var parent = btn.parent();
			var pId = parent.attr("id").split("-")[1];
			switch (type) {
				case 1:
					var pc = new Array();
					pc.push(PcList[pId]);
					SendWol(pc);
					break;
				case 2:
					var btnArray = ['否', '是'];
					mui.confirm('确认？', '删除设备', btnArray, function(e) {
						if (e.index == 1) {
							SendDelPC(pId);
						} else {}
					})
					break;
			}
		}
	</script>

	<script type="text/javascript">
		//websocket模块
		function WsConnect() {
			ShowLog("正在连接服务器...");
			MyWebSocket = new WebSocket(WebSocketURL);

			MyWebSocket.onopen = function(evt) {
				//StartKeepAlive(5); //保持心跳
				SetConnectStatus(true)
				//MyWebSocket.send('{"code":101,"name":"hello","type":1,"pc":[{"mac":"ff-ff-ff-ff-ff-ff","name":""}],"data":""}');
			};

			MyWebSocket.onclose = function() {
				//StopKeepAlive();
				SetConnectStatus(false)
				if (MyWebSocket.readyState == 3) {
					ShowLog("等待重连服务器...");
					setTimeout("WsConnect()", 3000); //断开后自动重连
				}
			};

			MyWebSocket.onerror = function(evt) {

			};

			MyWebSocket.onmessage = function(evt) {
				//console.log("Received Message: " + evt.data);
				var command = JSON.parse(evt.data);
				switch (command.code) {
					case codeWol:
						WolPC(command.pc)
						break;
					case codeSetPC:
						PcList = command.pc;
						ShowPCList();
						SetIsLogin(true);
						break;
					case codeExist:
						console.log(command.data)
						if (isLogIN) {
							LogIn();
						} else {
							LogOut();
							alert(command.data);
						}
						break;
					case codeError:
						alert(command.data);
						break;
					default:
						break;
				}
			};
		}

		function WebSocketColse() {
			if (isConnect) {
				MyWebSocket.close();
			}
		}

		function WebSocketSend(obj) {
			if (isConnect) {
				MyWebSocket.send(JSON.stringify(obj));
			}
		}

		function WolPC(pcList) {
			for (var i = 0; i < pcList.length; i++) {
				var mac = pcList[i].mac;
				var name = pcList[i].name;
				//UDPWOL("255.255.255.255", 6666, '00-15-5D-00-70-34');
				UDPWOL("255.255.255.255", WOLPort, mac);
			}
		}

		function SendHeartbeat() {
			WebSocketSend(GetWsMsgObj(codeHeartbeat, [], ""));
		}

		function SendWol(pc) {
			WebSocketSend(GetWsMsgObj(codeWol, pc, ""));
		}

		function SendGetPCList() {
			WebSocketSend(GetWsMsgObj(codeLogin, [], ""));
		}

		function SendLogout() {
			WebSocketSend(GetWsMsgObj(codeLogout, [], ""));
		}


		function SendSave() {
			WebSocketSend(GetWsMsgObj(codeSave, PcList, ""));
			SendGetPCList();
		}

		function SendDelPC(pid) {
			PcList.splice(pid, 1);
			SendSave();
		}

		function SendAddPC(name, mac, ip) {
			var has = false;
			for (var i = 0; i < PcList.length; i++) {
				if (PcList[i].mac == mac) {
					has = true;
					break;
				}
			}
			if (!has) {
				PcList.push({
					mac: mac,
					name: name,
					ip: ip
				});
				SendSave();
			}
			return !has;
		}

		function GetWsMsgObj(code, pc, data) {
			var obj = {
				code: code,
				name: Cname,
				type: Ctype,
				pc: pc,
				data: data
			}
			return obj;
		}
	</script>
	<script type="text/javascript">
		//唤醒模块
		function UDPWOL(addr, port, mac) {
			ShowLog("唤醒：" + mac);
			var DatagramSocket = plus.android.importClass("java.net.DatagramSocket");
			var DatagramPacket = plus.android.importClass("java.net.DatagramPacket");
			var InetAddress = plus.android.importClass("java.net.InetAddress");
			//var String = plus.android.importClass("java.lang.String");
			//var Byte = plus.android.importClass("java.lang.Byte");
			var StrictMode = plus.android.importClass("android.os.StrictMode");
			var Build = plus.android.importClass("android.os.Build");
			if (Build.VERSION.SDK_INT > 9) {
				var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
				StrictMode.setThreadPolicy(policy);
			}
			var udp = new DatagramSocket();
			var headData = strToByte('FF-FF-FF-FF-FF-FF-FF');
			var macData = strToByte(mac);
			for (var j = 0; j < 16; j++) {
				for (var i = 0; i < 6; i++) {
					macData.push(macData[i])
				}
			}
			var data = headData.concat(macData)
			for (var i = 0; i < data.length; i++) {
				if (data[i] > 127) {
					data[i] -= 256
				}
			}
			var packet = new DatagramPacket(data, data.length, InetAddress.getByName(addr), port);
			udp.send(packet);
			udp.close();
		}

		function strToByte(str) {
			var temp = str.split("-");
			for (var i = 0; i < temp.length; i++) {
				temp[i] = parseInt(temp[i], 16)
			}
			return temp
		}
	</script>
	<script type="text/javascript">
		function IsPCLive(ip) {
			var Process = plus.android.importClass("java.lang.Process");
			var Runtime = plus.android.importClass("java.lang.Runtime");
			var runtime = Runtime.getRuntime();
			var p = runtime.exec("ping -c 1 " + ip);
			// 			var InputStream = plus.android.importClass("java.io.InputStream");
			// 			var InputStreamReader = plus.android.importClass("java.io.InputStreamReader");
			// 			var BufferedReader = plus.android.importClass("java.io.BufferedReader");
			// 			var StringBuffer = plus.android.importClass("java.lang.StringBuffer");
			// 			bufin = new BufferedReader(new InputStreamReader(p.getInputStream()));
			// 			stringBuffer = new StringBuffer();
			// 			var content = "";
			// 			while ((content = bufin.readLine()) != null) {
			// 				stringBuffer.append(content);
			// 			}
			// 			//console.log(stringBuffer.toString())
			// 			ShowLog(stringBuffer.toString());
			var ret = p.waitFor();
			//ShowLog(ret);
			if (ret == 0) {
				return true;
			}
			return false;
		}

		function IsWifi() {
			if (GetNetworkType() == "WIFI") {
				return true;
			}
			return false;
		}

		function GetNetworkType() {
			var types = {};
			types[plus.networkinfo.CONNECTION_UNKNOW] = "网络连接状态未知";
			types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
			types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
			types[plus.networkinfo.CONNECTION_WIFI] = "WIFI";
			types[plus.networkinfo.CONNECTION_CELL2G] = "2G";
			types[plus.networkinfo.CONNECTION_CELL3G] = "3G";
			types[plus.networkinfo.CONNECTION_CELL4G] = "4G";
			return types[plus.networkinfo.getCurrentType()];
		}

		function GetIP() {
			var wifiManager, wifiInfo;
			var Context = plus.android.importClass("android.content.Context");
			var WifiManager = plus.android.importClass("android.net.wifi.WifiManager");
			var WifiInfo = plus.android.importClass("android.net.wifi.WifiInfo");
			wifiManager = plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);
			wifiInfo = wifiManager.getConnectionInfo();
			//dhcpInfo = wifiManager.getDhcpInfo();
			//console.log(wifiInfo.getIpAddress())
			return IntToIp(wifiInfo.getIpAddress());
		}

		function IntToIp(i) {
			return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
		}
	</script>
	<script type="text/javascript">
		// 对Date的扩展，将 Date 转化为指定格式的String   
		// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，   
		// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)   
		// 例子：   
		// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423   
		// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18   
		Date.prototype.Format = function(fmt) { //author: meizz   
			var o = {
				"M+": this.getMonth() + 1, //月份   
				"d+": this.getDate(), //日   
				"h+": this.getHours(), //小时   
				"m+": this.getMinutes(), //分   
				"s+": this.getSeconds(), //秒   
				"q+": Math.floor((this.getMonth() + 3) / 3), //季度   
				"S": this.getMilliseconds() //毫秒   
			};
			if (/(y+)/.test(fmt))
				fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt))
					fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			return fmt;
		}
	</script>
</html>
